import path from "path";
import { Request, Response } from "express";
import { Counter } from "../db";

export default {
  // 首页
  "GET /": async (req: Request, res: Response) => {
    res.sendFile(path.join(__dirname, "index.html"));
  },
  "GET /api/count": async (req: Request, res: Response) => {
    const result = await Counter.count();
    res.send({
      code: 0,
      data: result,
    });
  },
  // 更新计数
  "POST /api/count": async (req: Request, res: Response) => {
    const { action } = req.body;
    if (action === "inc") {
      await Counter.create();
    } else if (action === "clear") {
      await Counter.destroy({
        truncate: true,
      });
    }
    res.send({
      code: 0,
      data: await Counter.count(),
    });
  },
};
